package kxfang.com.home;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.android.arouter.facade.annotation.Route;

import kxfang.com.base.fragment.MvvmLazyFragment;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.utils.ToastUtil;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.bean.DataBean;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.router.RouterFragmentPath;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.home.adapter.HomeFragmentPageAdapter;
import kxfang.com.home.bean.GetListBean;
import kxfang.com.home.bean.HomeMainTypeModel;
import kxfang.com.home.databinding.HomeFragmentBinding;
import kxfang.com.home.databinding.HomeFragmentHomeBinding;
import kxfang.com.home.databinding.HomeGroupItemRvListBinding;
import kxfang.com.home.databinding.HomeTypeItemBinding;
import kxfang.com.home.discover.DisCoverFragment;
import kxfang.com.home.fragment.MainOneFragment;
import kxfang.com.home.nominate.NominateFragment;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.youth.banner.listener.OnBannerListener;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import kxfang.com.home.daily.DailyFragment;
import kxfang.com.home.par.GetListPar;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用模块: home
 * <p>
 * 类描述: 首页-fragment
 * <p>
 *
 * @author darryrzhoong
 * @since 2020-02-27
 */
@Route(path = RoutHub.PAGER_HOME)
public class HomeFragment extends MvvmLazyFragment<HomeFragmentBinding, IMvvmBaseViewModel> {

//    private HomeFragmentPageAdapter pageAdapter;

    private int[] images = {R.drawable.food_img, R.drawable.home_casual_icon, R.drawable.house_img, R.drawable.zhaopin_img,
            R.drawable.home_discount_icon, R.drawable.bianmin_img, R.drawable.home_qian_dao_icon, R.drawable.open_store_img};
    private String[] text = {"美食广场", "休闲玩乐", "来狗找房", "来狗招聘", "领券中心", "便民服务", "每日签到", "我要加入"};

    private List<HomeMainTypeModel> mainTypeModelList = new ArrayList<>();

    private FragmentStateAdapter pageAdapter;
    private TabLayoutMediator mediator;
    private String[] title = new String[]{"精选", "好店", "房圈"};
    private String[] downTitle = new String[]{"口碑热评", "每日好店", "真实好房"};
    private int activeColor = Color.parseColor("#FE2947");
    private int normalColor = Color.parseColor("#333333");
    private int down = Color.parseColor("#A9A9A9");
    //团购
    private BaseQuickAdapter<GetListBean.ActiveListBean, BaseViewHolder> groupAdapter;

    private long beforeTime = 0;

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        StatusBarUtil.setTopFragmentView(this, viewDataBinding.topView, R.color.common_colorWhite);
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(MainOneFragment.newInstance());
        fragments.add(MainOneFragment.newInstance());
        fragments.add(MainOneFragment.newInstance());
        pageAdapter = new FragmentStateAdapter(getChildFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return fragments.size();
            }
        };
        initView();

    }


    private void initView() {
        viewDataBinding.viewpager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        viewDataBinding.viewpager.setAdapter(pageAdapter);
        mediator = new TabLayoutMediator(viewDataBinding.xTabLayout, viewDataBinding.viewpager
                , (tab, position) -> {
            //这里可以自定义TabView
            TextView tabView = new TextView(getContext());
            TextView downTv = new TextView(getContext());
            LinearLayout parent = new LinearLayout(getContext());
            parent.setOrientation(LinearLayout.VERTICAL);
            parent.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                    , ViewGroup.LayoutParams.MATCH_PARENT));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f);

            int[][] states = new int[2][];
            states[0] = new int[]{android.R.attr.state_selected};
            states[1] = new int[]{};

            int[] colors = new int[]{activeColor, normalColor};
            int[] color = new int[]{activeColor, down};
            ColorStateList colorStateList = new ColorStateList(states, colors);
            ColorStateList colorState = new ColorStateList(states, color);
            tabView.setText(title[position]);
            tabView.setTextSize(17);
            tabView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            tabView.setTextColor(colorStateList);

            downTv.setText(downTitle[position]);
            downTv.setTextSize(11);
            downTv.setGravity(Gravity.CENTER_HORIZONTAL);
            downTv.setTextColor(colorState);

            parent.addView(tabView, params);
            parent.addView(downTv, params);

            tab.setCustomView(parent);
        });
        mediator.attach();
        for (int i = 0; i < images.length; i++) {
            HomeMainTypeModel mainTypeModel = new HomeMainTypeModel(text[i], images[i]);
            mainTypeModelList.add(mainTypeModel);
        }
        BaseQuickAdapter<HomeMainTypeModel, BaseViewHolder> mainTypeAdapter
                = new BaseQuickAdapter<HomeMainTypeModel, BaseViewHolder>(R.layout.home_type_item, mainTypeModelList) {
            @Override
            protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                DataBindingUtil.bind(viewHolder.itemView);
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable HomeMainTypeModel model) {
                if (model == null) {
                    return;
                }
                HomeTypeItemBinding binding = baseViewHolder.getBinding();
                if (binding != null) {
                    binding.setModel(model);
                    Glide.with(HomeFragment.this)
                            .load(model.getUrl())
                            .into(binding.image);
                }
            }
        };
        mainTypeAdapter.setOnItemClickListener((adapter, view, po) -> {
            switch (po) {
                case 0:
                    RouterUtils.navigate(RoutHub.FOOD_SQUARE);
//                    tostShow("敬请期待");
//                    intent.setClass(getActivity(), LifeServiceActivity.class);
//                    startActivity(intent);
                    break;
                case 1:
                    ToastUtils.showShort("敬请期待");
//                    intent.setClass(getActivity(), HouseMainActivity.class);
//                    startActivity(intent);
                    break;
                case 2:
                    ToastUtils.showShort("敬请期待");
//                    intent.setClass(getActivity(), ZhaoPinactivity.class);
//                    startActivity(intent);
                    break;
                case 3:
                    ToastUtils.showShort("敬请期待");
                    break;
                case 4:
                    Bundle bundle = new Bundle();
                    String url = "";
                    if (HawkUtil.getUserId() == null) {
                        url = Constant.LOAD_WEBVIEWURL.concat("/buyCupon.html?type=mobile");
                    } else {
                        url = Constant.LOAD_WEBVIEWURL.concat("/buyCupon.html?type=mobile")
                                .concat(String.format("&userid=%s", String.valueOf(HawkUtil.getUserId())));
                    }

                    bundle.putString("url", url);
                    bundle.putString("title", "领券中心");
                    RouterUtils.navigate(RoutHub.COUPONS_MAIN, bundle, getContext());
                    break;
                case 5:
                    ToastUtils.showShort("敬请期待");
                    break;
                case 6:
                    ToastUtils.showShort("敬请期待");
                    break;
                case 7:
                    ToastUtils.showShort("敬请期待");
                    break;
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);
        viewDataBinding.classRecycleView.setLayoutManager(layoutManager);
        viewDataBinding.classRecycleView.setAdapter(mainTypeAdapter);
    }

    private void GroupData() {
        GetListPar par = new GetListPar();
        par.setActiveStatu(0);
        par.setActiveType(1);
        par.setPageIndex(1);
        par.setPageSize(10);
        EasyHttp.post(HttpConfig.getList)
                .cacheKey(HttpConfig.getList.concat(HomeFragment.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<GetListBean>() {
                    @Override
                    public void onSuccess(GetListBean getListBean) {
//                        groupAdapter.clearData();
//                        groupAdapter.addAll(model.getActiveList());
//                        groupAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {

                    }
                });

    }
    private void Group() {
        groupAdapter=new BaseQuickAdapter<GetListBean.ActiveListBean, BaseViewHolder>(R.layout.home_group_item_rv_list, new ArrayList<>()) {
            @Override
            protected void onItemViewHolderCreated(@NotNull BaseViewHolder viewHolder, int viewType) {
                DataBindingUtil.bind(viewHolder.itemView);
            }
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, GetListBean.@Nullable ActiveListBean model) {
                HomeGroupItemRvListBinding binding = baseViewHolder.getBinding();
                if (model != null) {
                    binding.tvName.setText("【".concat(model.getBusinessName().concat("】").concat(model.getActiveTitle())));
                    binding.tvNum.setText("已抢：".concat(String.valueOf(model.getSoldNum())));
                    binding.tvPrice.setText(String.valueOf(model.getActivePrice()));
                    binding.tvOldPrice.setText("￥".concat(String.valueOf(model.getActiveYPrice())));
                    binding.tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                    List<DataBean> bannerList = new ArrayList<>();
                    for (int i = 0; i < model.getContentImgList().size(); i++) {
                        bannerList.add(new DataBean(Constant.PHOTO_SERVER_URL + model.getContentImgList().get(i).getUrl(), "", 1));
                    }
                    if (bannerList.size()==0){
                        bannerList.add(new DataBean(R.drawable.house_bitmap, "", 1));
                    }
                    binding.banner.isAutoLoop(false);
                    binding.banner.setUserInputEnabled(false);
//                    binding.banner.setAdapter(new MultipleTypesAdapter(getContext(), bannerList)).start();
                    binding.banner.setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(Object data, int position) {
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - beforeTime < 1000) {
                                return;
                            }
                            beforeTime = currentTime;
//                            Intent intent =new Intent(getContext(), GroupDetailActivity.class);
//                            intent.putExtra("id",model.getId());
//                            startActivity(intent);
                        }
                    });
                }
            }
        };
    }

    @Override
    public int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    public void onDestroyView() {
        mediator.detach();
        super.onDestroyView();
    }

    @Override
    protected void onRetryBtnClick() {

    }


}
